package com.example.easytts.controller

import com.example.easytts.model.User
import com.example.easytts.repository.UserRepository
import com.example.easytts.service.UserService
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import java.time.LocalDateTime
import org.springframework.security.core.annotation.AuthenticationPrincipal
import org.springframework.security.core.userdetails.User as SpringUser
import org.springframework.mail.javamail.JavaMailSender
import org.springframework.mail.SimpleMailMessage
import java.util.concurrent.ConcurrentHashMap

@RestController
@RequestMapping("/api/auth")
class AuthController(
    private val userService: UserService,
    private val userRepository: UserRepository,
    private val mailSender: JavaMailSender
) {
    data class AuthRequest(val username: String, val password: String, val code: String? = null)
    data class AuthResponse(val token: String)
    data class UserPointsRequest(val userId: Long, val points: Int)
    data class UserVipRequest(val userId: Long, val vipExpire: LocalDateTime)

    val codeCache = ConcurrentHashMap<String, String>() // 简单内存存储，生产建议用Redis

    @PostMapping("/register")
    fun register(@RequestBody req: AuthRequest): ResponseEntity<String> {
        return if (userService.register(req.username, req.password)) {
            ResponseEntity.ok("注册成功")
        } else {
            ResponseEntity.badRequest().body("用户名已存在")
        }
    }

    @PostMapping("/login")
    fun loginOrRegister(@RequestBody req: AuthRequest): ResponseEntity<Any> {
        // 校验验证码（注册或首次登录时必须）
        val user = userRepository.findByUsername(req.username)
        if (user == null) {
            // 注册时必须校验验证码
            if (req.code.isNullOrBlank()) {
                return ResponseEntity.badRequest().body(mapOf(
                    "code" to 400,
                    "message" to "验证码不能为空"
                ))
            }
            val cachedCode = codeCache[req.username]
            if (cachedCode == null || cachedCode != req.code) {
                return ResponseEntity.badRequest().body(mapOf(
                    "code" to 400,
                    "message" to "验证码错误"
                ))
            }
            codeCache.remove(req.username) // 验证码只能用一次
            // 自动注册
            val passwordEncoder = org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder()
            val newUser = com.example.easytts.model.User(
                username = req.username,
                password = passwordEncoder.encode(req.password)
            )
            userRepository.save(newUser)
            val token = userService.login(req.username, req.password)
            val savedUser = userRepository.findByUsername(req.username)
            return ResponseEntity.ok(mapOf(
                "code" to 200,
                "message" to "注册并登录成功",
                "token" to token,
                "user" to mapOf(
                    "id" to savedUser?.id,
                    "username" to savedUser?.username,
                    "role" to savedUser?.role,
                    "points" to savedUser?.points,
                    "vipExpire" to savedUser?.vipExpire
                )
            ))
        } else {
            // 已注册用户登录
            val passwordEncoder = org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder()
            if (passwordEncoder.matches(req.password, user.password)) {
                val token = userService.login(req.username, req.password)
                return ResponseEntity.ok(mapOf(
                    "code" to 200,
                    "message" to "登录成功",
                    "token" to token,
                    "user" to mapOf(
                        "id" to user.id,
                        "username" to user.username,
                        "role" to user.role,
                        "points" to user.points,
                        "vipExpire" to user.vipExpire
                    )
                ))
            } else {
                return ResponseEntity.badRequest().body(mapOf(
                    "code" to 400,
                    "message" to "密码错误"
                ))
            }
        }
    }

    // 查询当前用户信息
    @GetMapping("/me")
    fun me(@AuthenticationPrincipal principal: SpringUser?): ResponseEntity<Any> {
        if (principal == null) {
            return ResponseEntity.status(401).body(mapOf(
                "code" to 401,
                "message" to "未登录"
            ))
        }
        val user = userRepository.findByUsername(principal.username)
        return if (user != null) {
            ResponseEntity.ok(mapOf(
                "code" to 200,
                "message" to "success",
                "user" to mapOf(
                    "id" to user.id,
                    "username" to user.username,
                    "role" to user.role,
                    "points" to user.points,
                    "vipExpire" to user.vipExpire
                )
            ))
        } else {
            ResponseEntity.status(404).body(mapOf(
                "code" to 404,
                "message" to "用户不存在"
            ))
        }
    }

    // 管理员接口：查询所有用户
    @GetMapping("/all")
    fun all(): List<User> = userRepository.findAll()

    // 管理员接口：修改积分
    @PostMapping("/points")
    fun updatePoints(@RequestBody req: UserPointsRequest): ResponseEntity<Any> {
        val user = userRepository.findById(req.userId).orElse(null) ?: return ResponseEntity.status(404).body(mapOf("message" to "用户不存在"))
        userRepository.save(user.copy(points = req.points))
        return ResponseEntity.ok(mapOf("message" to "积分已更新"))
    }

    // 管理员接口：修改会员到期时间
    @PostMapping("/vip")
    fun updateVip(@RequestBody req: UserVipRequest): ResponseEntity<Any> {
        val user = userRepository.findById(req.userId).orElse(null) ?: return ResponseEntity.status(404).body(mapOf("message" to "用户不存在"))
        userRepository.save(user.copy(vipExpire = req.vipExpire))
        return ResponseEntity.ok(mapOf("message" to "会员时长已更新"))
    }

    // 管理员接口：删除用户
    @DeleteMapping("/{id}")
    fun delete(@PathVariable id: Long): ResponseEntity<Any> {
        userRepository.deleteById(id)
        return ResponseEntity.ok(mapOf("message" to "已删除"))
    }

    @PostMapping("/send-code")
    fun sendCode(@RequestBody req: Map<String, String>): ResponseEntity<Any> {
        val email = req["email"] ?: return ResponseEntity.badRequest().body(mapOf("message" to "邮箱不能为空"))
        val code = (100000..999999).random().toString()
        codeCache[email] = code
        val fromEmail = "scaudengqu@163.com" // 必须和spring.mail.username一致
        val message = SimpleMailMessage().apply {
            setFrom(fromEmail)
            setTo(email)
            setSubject("HanziUp 验证码")
            setText("您的验证码是: $code\n\n验证码有效期为10分钟。\n\n如果这不是您的操作，请忽略此邮件。")
        }
        println("[sendCode] 发送验证码到: $email, 验证码内容: $code")
        mailSender.send(message)
        return ResponseEntity.ok(mapOf("message" to "验证码已发送"))
    }

    @PostMapping("/verify-code")
    fun verifyCode(@RequestBody req: Map<String, String>): ResponseEntity<Any> {
        val email = req["email"] ?: return ResponseEntity.badRequest().body(mapOf("message" to "邮箱不能为空"))
        val code = req["code"] ?: return ResponseEntity.badRequest().body(mapOf("message" to "验证码不能为空"))
        if (codeCache[email] == code) {
            codeCache.remove(email)
            return ResponseEntity.ok(mapOf("message" to "验证通过"))
        }
        return ResponseEntity.badRequest().body(mapOf("message" to "验证码错误"))
    }
} 